<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 统一返回信息
 * @param $code
 * @param $data
 * @param $msg
 * @return array
 */
function msg($code, $data, $msg)
{
    return compact('code', 'data', 'msg');
}

/**
 * 对象转换成数组
 * @param $obj
 * @return array
 */
function objToArray($obj)
{
    return json_decode(json_encode($obj), true);
}

/**
 * 获取毫米时间戳
 * @return string
 */
function getMillisecond() {
    list($t1, $t2) = explode(' ', microtime());
    return sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
}

/**
 * 调用别人接口数据的一个方法（固定形式）
 * @param $url
 * @param $keysArr
 * @return mixed
 */
function httpGet($url, $keysArr) {
    $combined = httpcombineURL($url, $keysArr);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $combined);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
}

/**
 * 调用别人接口数据的一个方法（固定形式）
 * @param $url
 * @param array $data
 * @return mixed
 */
function httpPost($url, $data=array()) {
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 500);//设置超时
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);//设置header
    curl_setopt($ch, CURLOPT_POST, TRUE);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));//请求数据$json
    $res = curl_exec($ch); //运行curl
    curl_close($ch);
    unset($ch);
    return $res;
}

/**
 * combineURL
 * 拼接url
 * @param string $baseURL   基于的url
 * @param array  $keysArr   参数列表数组
 * @return string           返回拼接的url
 */
function httpcombineURL($baseURL, $keysArr){
    if(empty($keysArr)){
        return $baseURL;
    }
    $combined = $baseURL."?";
    $valueArr = array();

    foreach($keysArr as $key => $val){
        $valueArr[] = "$key=$val";
    }

    $keyStr = implode("&",$valueArr);
    $combined .= ($keyStr);

    return $combined;
}